package com.wushijia.datastructure;

public class BSArray
{
    public static int binarySearch(Comparable[] table, Comparable cobj, int low, int high) 
    {                                                 
        if (table!=null && cobj!=null)
        {
            while (low<=high)                       
            {
                int mid = (low+high)/2;                 
                System.out.print(table[mid]+" ?   ");
                if (cobj.compareTo(table[mid])==0)      
                    return mid;                        
                else
                    if (cobj.compareTo(table[mid])<0)     
                        high = mid-1;                 
                    else
                        low = mid+1;                 
            }
        }
        return -1;                                 
    }  
    
    public static int binarySearch(Comparable[] table, Comparable cobj)  
    {                     
        return binarySearch(table, cobj, 0, table.length-1);
    }  
    
    public static void print(Object[] table)                  
    {
        if (table!=null)
            for (int i=0; i<table.length; i++)
                System.out.print(" "+table[i]);
        System.out.println();
    }
    
    public static void main(String[] args)
    {
        Integer[] table ={new Integer(8),new Integer(17),new Integer(26),new Integer(32),new Integer(40),new Integer(72),new Integer(87),new Integer(99)};        
        System.out.print("array table is:");
        print(table);
        Integer key=new Integer(40);
        System.out.println("\n"+key+", "+((binarySearch(table,key)==-1)?"not find!":"find!"));
        key=new Integer(25);
        System.out.println("\n"+key+", "+((binarySearch(table,key)==-1)?"not find!":"find!"));
    }
}

